
package com.witmed.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import javax.swing.text.rtf.RTFEditorKit;

import org.apache.tomcat.jni.User;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.witmed.entity.Appointment;
import com.witmed.entity.UserInfo;
import com.witmed.service.UserService;
import com.witmed.service.impl.UserServiceImpl;
import com.witmed.util.MD5;
import com.witmed.util.PhoneCode;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {
	private UserService userService = new UserServiceImpl();
	private static final long serialVersionUID = 1L;
	private String phonemsg = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");

		if ("userLogin".equals(op)) {// 用户登录验证
			doUserLogin(request, response);
		} else if ("findUserInfo".equals("op")) {// 查找用户信息
			doFindUserInfo(request, response);
		} else if ("findUserAppiontmentInfo".equals(op)) { // 查找问诊信息
			doFindAppiontmentInfo(request, response);
		} else if ("panduan".equals(op)) {// 密码判断
			doFindUserInfo(request, response);
		} else if ("updataUserInfo".equals(op)) {// 修改用户信息
			doUpdataUserInfo(request, response);
		} else if ("updateUserByPhone".equals(op)) {// 根据手机号修改用户
			doUpdataUserInfoByPhone(request, response);
		} else if ("checkUserName".equals(op)) {// 根验证用户名是否存在
			doCheckUserName(request, response);
		} else if ("checkPhone".equals(op)) {// 验证手机号是否存在
			doCheckPhone(request, response);
		} else if ("checkCode".equals(op)) {// 验证手机验证码
			doCheckCode(request, response);
		} else if ("register".equals(op)) {// 注册用户信息
			doRegister(request, response);
		} else if ("logout".equals(op)) {
			doLogOut(request, response);
		}

	}

	// 注销登录
	private void doLogOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		response.sendRedirect("userRegisterAndLogin/pages/userLogin.jsp");
	}

	/**
	 * 修改用户信息 ChenYouming
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void doUpdataUserInfo(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String number = request.getParameter("number");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		if ("男".equals(sex)) {
			sex = "1";
		} else {
			sex = "0";
		}
		String age = request.getParameter("age");
		String realname = request.getParameter("realname");
		String ident = request.getParameter("ident");
		String userTel = request.getParameter("userTel");
		// 获取单个文件
		Part part = request.getPart("file");
		UserInfo user = null;
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层
			HttpSession session = request.getSession();
			UserInfo userInfo = (UserInfo) session.getAttribute("user");
			user = new UserInfo(Integer.parseInt(number), name, userInfo.getUserPassword(), Integer.parseInt(age),
					userTel, Integer.parseInt(sex), realname, ident, userInfo.getUserPicturePath());
			userService.update(user);
		} else {
			// 有上传
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
				response.sendRedirect("back/userBackindex.jsp?fileuploaderror=notallowtype");
				return;
			} else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int) ((Math.random() * 9 + 1) * 1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);

				// 定义文件存储目录
				File file = new File("E:\\fileupload\\images");

				StringBuffer filePath = new StringBuffer();

				filePath.append(file.getPath()).append(File.separator).append(fileName);

				// 将文件写入指定位置
				part.write(filePath.toString());
				// 调用业务逻辑层
				HttpSession session = request.getSession();
				UserInfo object = (UserInfo) session.getAttribute("user");
				user = new UserInfo(Integer.parseInt(number), name, object.getUserPassword(), Integer.parseInt(age),
						userTel, Integer.parseInt(sex), realname, ident, fileName.toString());
				userService.update(user);
			}

		}
	}

	/**
	 * luyunxiao 通过手机号修改用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void doUpdataUserInfoByPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userTel = request.getParameter("phone");
		String password = request.getParameter("password");
		System.out.println(userTel+"        "+password);
		MD5 md5 = new MD5();
		// 调用业务层
		UserInfo user = new UserInfo(null, null, md5.MD5Encode(password, "utf-8"), null, userTel, null, null, null, null);
		boolean i = userService.updateByTel(user);
		response.getWriter().print(i);
	}

	
	/**
	 * luyunxiao 用户登录验证
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doUserLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String loginType = request.getParameter("loginType");// 判断登录账号是userName还是phone
		String loginName = request.getParameter("loginName");// 登录账号
		String userPassword = request.getParameter("password");
		MD5 md5 = new MD5();
		String md5Encode = md5.MD5Encode(userPassword, "utf-8");// MD5密码加密

		List<UserInfo> list = null;
		ObjectMapper objectMapper = new ObjectMapper();
		String json = "";
		// 调用业务层
		if ("userName".equals(loginType)) {
			list = userService.loginByUserNameAndPassword(loginName, md5Encode);
			if (list.isEmpty()) {
				// 登录失败
				json = objectMapper.writeValueAsString("fail");
			} else {
				// 登录成功
				// 存储到session会话
				UserInfo user = list.get(0);
				HttpSession session = request.getSession();
				session.setMaxInactiveInterval(1800);
				session.setAttribute("user", user);
				// 响应
				json = objectMapper.writeValueAsString(user);
			}
		} else if ("userTel".equals(loginType)) {
			// 根据手机号获取手机验证码
			String code = request.getParameter("captcha");
			if(phonemsg.equals(code)) {
				// 登录成功
				// 存储到session会话
				UserInfo user = userService.findByUserTel(loginName).get(0);
				HttpSession session = request.getSession();
				session.setMaxInactiveInterval(1800);
				session.setAttribute("user", user);
				// 响应
				json = objectMapper.writeValueAsString(user);
			}else {
				// 登录失败
				json = objectMapper.writeValueAsString("fail");
			}
		}
		response.getWriter().print(json);

	}

	/**
	 * ChenYouming 鏌ヨ鐢ㄦ埛闂瘖璁板綍淇℃伅
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doFindAppiontmentInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		String number = request.getParameter("number");
		List<Appointment> userInquirieslist = userService.queryByUserId(number);
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(userInquirieslist);
		response.getWriter().print(json);
	}

	/**
	 * ChenYouming 鏌ヨ鐢ㄦ埛涓汉淇℃伅
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doFindUserInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		String number = request.getParameter("number");
		List<UserInfo> userInfoslist = userService.queryByUserIdOrUserTel(number);
		System.out.println(userInfoslist);
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(userInfoslist);
		System.out.println("鐢ㄦ埛锛�" + json);
		response.getWriter().print(json);
	}

	/**
	 * luyunxiao 注册时验证用户名是否存在
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doCheckUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		List<UserInfo> list = userService.findByUserName(username);
		boolean isExist = true;
		if (list.isEmpty()) {
			// 用户名不存在,可用
			isExist = false;
		}
		response.getWriter().print(isExist);
	}

	/**
	 * luyunxiao 注册时验证手机号是否存在
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doCheckPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String phone = request.getParameter("phone");
		List<UserInfo> list = userService.findByUserTel(phone);
		boolean isExist = true;
		if (list.isEmpty()) {
			// 手机号不存在,可用
			isExist = false;
		}
		response.getWriter().print(isExist);
	}

	/**
	 * luyunxiao 注册时验证手机验证码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String phone = request.getParameter("phone");
		// 根据手机号获取手机验证码
		PhoneCode phoneCode = new PhoneCode();
		phonemsg = phoneCode.getPhonemsg(phone);
		// 响应文本数据
		PrintWriter out = response.getWriter();
		out.print(phonemsg);
	}

	/**
	 * luyunxiao 注册用户信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userName = request.getParameter("username");
		String userPassword = request.getParameter("password");
		String userTel = request.getParameter("text");
		MD5 md5 = new MD5();
		String md5Encode = md5.MD5Encode(userPassword, "utf-8");// MD5密码加密
		String picPath = "userRegisterAndLogin/images/user.png";
		boolean i = userService
				.insert(new UserInfo(null, userName, md5Encode, null, userTel, null, null, null, picPath));
		// 响应文本数据
		PrintWriter out = response.getWriter();
		out.print(i);
	}

}
